//
// Created by wujehy on 2020/7/8.
//

#ifndef GEEJOAN_MYSQL_DATABASE_H
#define GEEJOAN_MYSQL_DATABASE_H

#include "Exception.h"
#include <string>

namespace GeeJoan
{
    namespace MySQL
    {
        class DataBase
        {
            std::string m_host;
            unsigned int m_port;
            std::string m_database;
            std::string m_username;
            std::string m_password;

            MYSQL *m_db_hander = nullptr;

        public:
            DataBase(
                    const std::string &mHost, unsigned int mPort,
                    const std::string &mDatabase = std::string( "" ),
                    const std::string &mUsername = std::string( "root" ),
                    const std::string &mPassword = std::string( "" ));

            DataBase(
                    const std::string &mHost, const std::string &mDatabase = std::string( "" ),
                    const std::string &mUsername = std::string( "root" ),
                    const std::string &mPassword = std::string( "" )) :
                    DataBase( mHost, 3306, mDatabase, mUsername,
                              mPassword )
            {};

            virtual ~DataBase();

            int exec(std::string &sql)
            {
                return exec( sql.c_str());
            }

            int exec(const char *sql);

            void check(const int code) const
            {
                if (!m_db_hander)
                {
                    throw Exception( "DataBase is not open ", -1 );
                }
                if (code != 0)
                {
                    throw Exception( m_db_hander );
                }
            }

            MYSQL *getHander();

            int changeDB(std::string dbName)
            {
                return changeDB( dbName.c_str());
            }

            int changeDB(const char *dbName);
        };

    }
}


#endif //GEEJOAN_MYSQL_DATABASE_H
